<?php include_once($_SERVER['DOCUMENT_ROOT']."/controller/common/common_setting_unit.php");         // 引入通用的设置文件 ?>

<?php
// upload_handler.php - 上传处理文件

// 检查是否为POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['code' => 405, 'msg' => 'Method Not Allowed']);
    exit;
}

try {
    // 检查是否有上传文件
    if (!isset($_FILES) || count($_FILES) == 0) {
        throw new Exception('没有上传文件');
    }

    // 获取上传文件信息
    $file = $_FILES['file']; // 默认字段名

    // 检查上传错误
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('文件上传出错: ' . $file['error']);
    }

// 先封装一个永远存在的助手
// PHP 5.6 可用（去掉类型声明）
    if (!function_exists('get_mime_type')) {
        function get_mime_type($tmpPath)
        {
            if (function_exists('finfo_file')) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $type  = finfo_file($finfo, $tmpPath);
                finfo_close($finfo);
                return $type;
            }
            // fallback 幻数
            $fh   = fopen($tmpPath, 'rb');
            $head = fread($fh, 3);
            fclose($fh);
            $map = array(
                "\xFF\xD8\xFF" => 'image/jpeg',
                "\x89\x50\x4E" => 'image/png',
                "\x47\x49\x46" => 'image/gif',
            );
            return isset($map[$head]) ? $map[$head] : 'application/octet-stream';
        }
    }

// 你的原逻辑改成这样
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    $fileType     = get_mime_type($file['tmp_name']);
    if (!in_array($fileType, $allowedTypes, true)) {
        throw new Exception('只允许上传 JPEG、PNG、GIF 格式的图片');
    }



    // 验证文件大小（例如限制为5MB）
    $maxFileSize = 1 * 1024 * 1024;
    if ($file['size'] > $maxFileSize) {
        throw new Exception('为优化系统数据，请限制文件大小不能超过800k，请调整分辨率或压缩图片');
    }











    // 生成唯一文件名
    $extension        = pathinfo($file['name'], PATHINFO_EXTENSION);
    $file_name_serial = date('YmdHis') . "-" . rand(10000, 99990);
    $newFileName      = $file_name_serial . '.' . $extension;
    $webpFileName     = $file_name_serial . '.webp';
    $jpegFileName     = $file_name_serial . '.jpg';

    // 设置上传目录（请根据实际情况修改）
    $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploadfiles/temp/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }


    //上传之后的名字
    $uploadPath     = $uploadDir . $newFileName;
    //转换格式之后的名字
    $webpUploadPath = $uploadDir . $webpFileName;
    $jpegUploadPath = $uploadDir . $jpegFileName;



    // 先保存原始文件
    // 移动上传文件
    if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
        throw new Exception('原始文件保存失败');
    }





    //判断是否支持转换webp
    $webpSupported = function_exists('imagewebp');


    // 转换图片为WebP格式
    $webconverted = false;
    $jpegConverted = false;
    $convertError = '';


    if ($webpSupported) {
        // 转换图片为WebP格式
        switch($fileType) {
            case 'image/jpeg':
                if (function_exists('imagecreatefromjpeg') && function_exists('imagewebp')) {
                    $image = imagecreatefromjpeg($uploadPath);
                    if ($image !== false) {
                        if (imagewebp($image, $webpUploadPath, 80)) { // 80% 质量
                            $webconverted = true;
                        } else {
                            $convertError = 'JPEG转WebP失败';
                        }
                        imagedestroy($image);
                    } else {
                        $convertError = '无法读取JPEG文件';
                    }
                } else {
                    $convertError = '服务器不支持JPEG转WebP';
                }
                break;
            case 'image/png':
                if (function_exists('imagecreatefrompng') && function_exists('imagewebp')) {
                    $image = imagecreatefrompng($uploadPath);
                    if ($image !== false) {
                        imagealphablending($image, false);
                        imagesavealpha($image, true);
                        if (imagewebp($image, $webpUploadPath, 80)) { // 80% 质量
                            $webconverted = true;
                        } else {
                            $convertError = 'PNG转WebP失败';
                        }
                        imagedestroy($image);
                    } else {
                        $convertError = '无法读取PNG文件';
                    }
                } else {
                    $convertError = '服务器不支持PNG转WebP';
                }
                break;
            case 'image/gif':
                if (function_exists('imagecreatefromgif') && function_exists('imagewebp')) {
                    $image = imagecreatefromgif($uploadPath);
                    if ($image !== false) {
                        if (imagewebp($image, $webpUploadPath, 80)) { // 80% 质量
                            $webconverted = true;
                        } else {
                            $convertError = 'GIF转WebP失败';
                        }
                        imagedestroy($image);
                    } else {
                        $convertError = '无法读取GIF文件';
                    }
                } else {
                    $convertError = '服务器不支持GIF转WebP';
                }
                break;
        }
    }
    else {
        // 不支持webp则转换为jpg
        switch($fileType) {
            case 'image/jpeg':
                // JPEG文件不需要转换
                break;
            case 'image/png':
                // PNG转换为JPEG
                if (function_exists('imagecreatefrompng') && function_exists('imagejpeg')) {
                    $image = imagecreatefrompng($uploadPath);
                    if ($image !== false) {
                        // 处理透明背景，填充白色
                        $white = imagecolorallocate($image, 255, 255, 255);
                        imagefill($image, 0, 0, $white);
                        imagealphablending($image, true);
                        imagesavealpha($image, false);

                        if (imagejpeg($image, $jpegUploadPath, 80)) { // 80% 质量
                            $jpegConverted = true;
                        }
                        imagedestroy($image);
                    }
                }
                break;
            case 'image/gif':
                // GIF转换为JPEG
                if (function_exists('imagecreatefromgif') && function_exists('imagejpeg')) {
                    $image = imagecreatefromgif($uploadPath);
                    if ($image !== false) {
                        // 创建新的真彩色图像
                        $newImage = imagecreatetruecolor(imagesx($image), imagesy($image));
                        // 填充白色背景
                        $white = imagecolorallocate($newImage, 255, 255, 255);
                        imagefilledrectangle($newImage, 0, 0, imagesx($newImage), imagesy($newImage), $white);
                        // 将GIF图像复制到新图像上
                        imagecopy($newImage, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));

                        if (imagejpeg($newImage, $jpegUploadPath, 80)) { // 80% 质量
                            $jpegConverted = true;
                        }
                        imagedestroy($image);
                        imagedestroy($newImage);
                    }
                }
                break;
        }
    }













// 如果WebP转换成功，也返回WebP文件路径，否则返回错误信息
    if ($webconverted)
    {
        $responseData = [
            'src' => '/uploadfiles/temp/' . $webpFileName,
            'name' => $webpFileName
        ];
        $msg="上传成功,并转换webp";

    }
    elseif($jpegConverted)
    {
        $responseData = [
            'src' => '/uploadfiles/temp/' . $jpegFileName,
            'name' => $jpegFileName
        ];
        $msg="上传成功,并转换jpeg";

    }else {


        $responseData = [
            'src' => '/uploadfiles/temp/' . $newFileName,
            'name' => $newFileName
        ];
        $msg = "上传成功,但转换格式失败。".$convertError ?: '未知错误导致WebP转换失败';
    }










    // 返回成功响应
    echo json_encode([
        'code' => 0,
        'msg' => $msg,
        'data' => $responseData
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    // 返回错误响应
    echo json_encode([
        'code' => 1,
        'msg' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>
